#include "timer_manager.h"

#include <iostream>
#include <sys/time.h>
#include <queue>
#include <memory>

#include "mutex_guard.h"
#include "request_data.h"


MyTimer::MyTimer(RequestDataPtr requestData, int timeout):
        requestData_(requestData), deleted_(false) 
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    expiredTime_ = 1000 * (tv.tv_sec) + (tv.tv_usec) / 1000 + timeout;
}

MyTimer::~MyTimer() {
    if(requestData_){
        requestData_->HandleClose();
    }
}

bool MyTimer::IsExpired(){ 
    struct timeval tv;
    gettimeofday(&tv, NULL);
    long cur = 1000 * (tv.tv_sec) + (tv.tv_usec) / 1000;
    //如果过期自动设置删除标志位
    if (cur >= expiredTime_){
        deleted_ = true;
        return true;
    }
    return false;
}

bool MyTimer::IsDeleted() {
    return deleted_;
}

void MyTimer::SetDeleted() {  
    // 将reqeustData指针设为空，原对象不受影响(use_count 减1)
    requestData_.reset();
    deleted_ = true;
}

time_t MyTimer::GetExpTime() const {
    return expiredTime_;
}


TimerManager& TimerManager::Instance(){
    static TimerManager timerManager;
    return timerManager; 
}

TimerManager::TimerManager(){}

TimerManager::~TimerManager(){
    // 析构时将定时器队列清空, 确保资源正确释放
    MutexGuard mutexGuard(timerQueueLocker_);
    while(!timerQueue_.empty()){ 
        auto timer = timerQueue_.top();
        timerQueue_.pop();
        timer.reset();
    }
}

/***
 * 处理超时的计时器，直至遇到一个未超时计时器
 */
void TimerManager::HandleTimer(){ 
    MutexGuard mutexGuard(timerQueueLocker_);
    while(!timerQueue_.empty()){ 
        auto timer = timerQueue_.top();
        if(!(timer->IsDeleted() || timer->IsExpired())){
            break;
        }
        timerQueue_.pop();
    }
}

void TimerManager::InsertTimer(std::shared_ptr<MyTimer> timer){
    MutexGuard mutexGuard(timerQueueLocker_);
    timerQueue_.push(timer);
}
